package common

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"gorm.io/driver/mysql"
	_ "gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

var DB *gorm.DB
var err error

type AppConfig struct {
	Db DBConfig `yaml:"db"`
	//Redis    string   `yaml:"redis"`
	//Server   string   `yaml:"server"`
}

type DBConfig struct {
	Host     string `yaml:"host" `
	Port     string `yaml:"port" `
	Driver   string `yaml:"driver" `
	Username string `yaml:"username" `
	Password string `yaml:"password" `
	Dbname   string `yaml:"dbname" `
	Charset  string `yaml:"charset" `
}

type Redis struct {
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	Password string `yaml:"password"`
}

type Server struct {
	Port string `yaml:"port"`
	Env  string `yaml:"env"`
}

func loadConfig() (*AppConfig, error) {
	// 假定配置文件名为config.yaml，位于程序的可执行文件同级目录下
	yamlFile, err := os.ReadFile("config/config.yaml")
	if err != nil {
		return nil, fmt.Errorf("failed to read config file: %w", err)
	}

	// 解析YAML数据到Config结构体
	var appConfig AppConfig
	if err := yaml.Unmarshal(yamlFile, &appConfig); err != nil {
		log.Fatalf("Failed to unmarshal YAML: %v", err)
	}

	return &appConfig, nil
}

func init() {
	appConfig, err := loadConfig()
	if err != nil {
		log.Fatalf("Error loading config: %v", err)
	}
	fmt.Println("输出ip ", appConfig.Db.Driver)
	mysqlurls := appConfig.Db.Host + ":" + appConfig.Db.Port
	dsn := appConfig.Db.Username + ":" + appConfig.Db.Password + "@tcp(" + mysqlurls + ")/" + appConfig.Db.Dbname + "?charset=utf8mb4&parseTime=True&loc=Local"
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second,  // 慢 SQL 阈值
			LogLevel:      logger.Error, // Log level
			Colorful:      true,         // 彩色打印
		},
	)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: newLogger})
	if err != nil {
		fmt.Println("异常错误")
	}
}
